package com.wdb.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author longshiyu
 */
public abstract class JacksonUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtils.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String convert(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.error("convert error : {}", e.getMessage());
            }
            return null;
        }
    }

    public static <T> T parse(String json, Class<T> clz) {
        try {
            return MAPPER.readValue(json, clz);
        } catch (IOException e) {
            e.printStackTrace();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.error("parse error : {}", e.getMessage());
            }
            return null;
        }
    }

    public static <T> T parse(InputStream in, Class<T> clz) {
        try {
            return MAPPER.readValue(in, clz);
        } catch (IOException e) {
            e.printStackTrace();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.error("generic parse error : {}", e.getMessage());
            }
            return null;
        }
    }
}
